package com.ruoyi.common.utils;

import eu.bitwalker.useragentutils.UserAgent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * User-Agent解析工具类
 * 提供更准确的浏览器和操作系统识别
 *
 * @author ruoyi
 */
public class UserAgentUtils {
    
    private static final Logger log = LoggerFactory.getLogger(UserAgentUtils.class);

    /**
     * 解析浏览器名称
     *
     * @param userAgentString User-Agent字符串
     * @return 浏览器名称
     */
    public static String parseBrowserName(String userAgentString) {
        if (StringUtils.isEmpty(userAgentString)) {
            return "Unknown";
        }
        
        try {
            // 优先检测移动应用环境（这些需要手动检测，因为UserAgentUtils库识别不准确）
            if (userAgentString.contains("MiniProgram")) {
                // 微信小程序
                String wechatVersion = extractWechatVersion(userAgentString);
                return "微信小程序" + (wechatVersion != null ? " " + wechatVersion : "");
            } else if (userAgentString.contains("MicroMessenger")) {
                // 微信浏览器
                String wechatVersion = extractWechatVersion(userAgentString);
                return "微信浏览器" + (wechatVersion != null ? " " + wechatVersion : "");
            } else if (userAgentString.contains("QQ/") && !userAgentString.contains("MQQBrowser")) {
                // QQ应用
                String qqVersion = extractSimpleVersion(userAgentString, "QQ/");
                return "QQ" + (qqVersion != null ? " " + qqVersion : "");
            } else if (userAgentString.contains("MQQBrowser")) {
                // QQ浏览器
                String qqVersion = extractSimpleVersion(userAgentString, "MQQBrowser/");
                return "QQ浏览器" + (qqVersion != null ? " " + qqVersion : "");
            } else if (userAgentString.contains("AlipayClient")) {
                // 支付宝
                String alipayVersion = extractSimpleVersion(userAgentString, "AlipayClient/");
                return "支付宝" + (alipayVersion != null ? " " + alipayVersion : "");
            } else if (userAgentString.contains("DingTalk")) {
                // 钉钉
                String dingVersion = extractSimpleVersion(userAgentString, "DingTalk/");
                return "钉钉" + (dingVersion != null ? " " + dingVersion : "");
            } else if (userAgentString.contains("BytedanceWebview")) {
                // 抖音
                String ttVersion = extractSimpleVersion(userAgentString, "BytedanceWebview/");
                return "抖音" + (ttVersion != null ? " " + ttVersion : "");
            }
            UserAgent userAgent = UserAgent.parseUserAgentString(userAgentString);
            String browserName = userAgent.getBrowser().getName();
            String browserVersion = userAgent.getBrowserVersion() != null ? userAgent.getBrowserVersion().toString() : null;
            if (browserVersion != null && !browserVersion.isEmpty()) {
                String[] versionParts = browserVersion.split("\\.");
                if (versionParts.length >= 2) {
                    browserVersion = versionParts[0] + "." + versionParts[1];
                } else if (versionParts.length == 1) {
                    browserVersion = versionParts[0];
                }
                
                return browserName + " " + browserVersion;
            } else {
                return browserName != null ? browserName : "Unknown";
            }
        } catch (Exception e) {
            log.warn("解析User-Agent异常: {}", e.getMessage());
            return "Unknown";
        }
    }

    /**
     * 解析操作系统名称
     *
     * @param userAgentString User-Agent字符串
     * @return 操作系统名称
     */
    public static String parseOsName(String userAgentString) {
        if (StringUtils.isEmpty(userAgentString)) {
            return "Unknown";
        }
        try {
            UserAgent userAgent = UserAgent.parseUserAgentString(userAgentString);
            String osName = userAgent.getOperatingSystem().getName();
            // 特殊处理一些移动操作系统版本识别问题
            if (userAgentString.contains("Android")) {
                // 尝试从User-Agent中提取更准确的Android版本
                String androidVersion = extractAndroidVersion(userAgentString);
                if (StringUtils.isNotEmpty(androidVersion)) {
                    return "Android " + androidVersion;
                }
            } else if (userAgentString.contains("iPhone OS") || userAgentString.contains("CPU OS")) {
                // 尝试从User-Agent中提取iOS版本
                String iosVersion = extractIosVersion(userAgentString);
                if (StringUtils.isNotEmpty(iosVersion)) {
                    return "iOS " + iosVersion;
                }
            }
            return osName;
        } catch (Exception e) {
            return "Unknown";
        }
    }


    /**
     * 从User-Agent中提取Android版本号
     *
     * @param userAgentString User-Agent字符串
     * @return Android版本号
     */
    private static String extractAndroidVersion(String userAgentString) {
        try {
            // 匹配 Android x.x 或 Android x.x.x 格式
            int androidIndex = userAgentString.indexOf("Android ");
            if (androidIndex != -1) {
                String afterAndroid = userAgentString.substring(androidIndex + 8);
                int endIndex = afterAndroid.indexOf(";");
                if (endIndex == -1) {
                    endIndex = afterAndroid.indexOf(")");
                }
                if (endIndex == -1) {
                    endIndex = afterAndroid.indexOf(" ");
                }
                if (endIndex > 0) {
                    return afterAndroid.substring(0, endIndex).trim();
                }
            }
        } catch (Exception e) {
            // 忽略异常，返回null
        }
        return null;
    }

    /**
     * 从User-Agent中提取iOS版本号
     *
     * @param userAgentString User-Agent字符串
     * @return iOS版本号
     */
    private static String extractIosVersion(String userAgentString) {
        try {
            // 匹配 OS x_x 或 iPhone OS x_x 格式
            String pattern = userAgentString.contains("iPhone OS") ? "iPhone OS " : "OS ";
            int osIndex = userAgentString.indexOf(pattern);
            if (osIndex != -1) {
                String afterOs = userAgentString.substring(osIndex + pattern.length());
                int endIndex = afterOs.indexOf(" ");
                if (endIndex > 0) {
                    return afterOs.substring(0, endIndex).replace("_", ".");
                }
            }
        } catch (Exception e) {
            // 忽略异常，返回null
        }
        return null;
    }
    
    /**
     * 简单提取版本号（用于移动应用）
     *
     * @param userAgentString User-Agent字符串
     * @param prefix          前缀
     * @return 版本号
     */
    private static String extractSimpleVersion(String userAgentString, String prefix) {
        try {
            int prefixIndex = userAgentString.indexOf(prefix);
            if (prefixIndex != -1) {
                String afterPrefix = userAgentString.substring(prefixIndex + prefix.length());
                int endIndex = afterPrefix.indexOf(" ");
                if (endIndex == -1) {
                    endIndex = afterPrefix.indexOf(";");
                }
                if (endIndex == -1) {
                    endIndex = afterPrefix.indexOf(")");
                }
                if (endIndex > 0) {
                    String version = afterPrefix.substring(0, endIndex).trim();
                    // 简化版本号
                    String[] versionParts = version.split("\\.");
                    if (versionParts.length >= 2) {
                        return versionParts[0] + "." + versionParts[1];
                    } else if (versionParts.length == 1) {
                        return versionParts[0];
                    }
                    return version;
                }
            }
        } catch (Exception e) {
            // 忽略异常
        }
        return null;
    }
    
    /**
     * 从User-Agent中提取微信版本号
     * 微信版本格式：MicroMessenger/6.6.1.1220(0x26060135) 或 MicroMessenger/8.0.40
     *
     * @param userAgentString User-Agent字符串
     * @return 微信版本号
     */
    private static String extractWechatVersion(String userAgentString) {
        try {
            int messengerIndex = userAgentString.indexOf("MicroMessenger/");
            if (messengerIndex != -1) {
                String afterMessenger = userAgentString.substring(messengerIndex + 15);
                int endIndex = afterMessenger.indexOf("(");
                if (endIndex == -1) {
                    endIndex = afterMessenger.indexOf(" ");
                }
                if (endIndex == -1) {
                    endIndex = afterMessenger.indexOf(")");
                }
                if (endIndex > 0) {
                    String version = afterMessenger.substring(0, endIndex).trim();
                    // 简化版本号，只保留前两段
                    String[] versionParts = version.split("\\.");
                    if (versionParts.length >= 2) {
                        return versionParts[0] + "." + versionParts[1];
                    } else if (versionParts.length == 1) {
                        return versionParts[0];
                    }
                    return version;
                }
            }
        } catch (Exception e) {
            // 忽略异常，返回null
        }
        return null;
    }
}
